package com.himiotech.core.project.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.himiotech.core.framework.helper.anno.DataScope;
import com.himiotech.core.framework.helper.constant.UserConstants;
import com.himiotech.core.framework.helper.exception.HimioException;
import com.himiotech.core.framework.helper.model.SimpleDataTree;
import com.himiotech.core.project.data.mapper.DeptMapper;
import com.himiotech.core.project.data.mapper.UserMapper;
import com.himiotech.core.project.model.entity.Dept;
import com.himiotech.core.project.model.entity.role.Role;
import com.himiotech.core.project.model.entity.user.User;
import com.himiotech.core.project.model.metadata.DeptMetadata;
import com.himiotech.core.project.service.IDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 部门管理 服务实现
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Dept> selectDeptList(Dept dept) {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SimpleDataTree<Dept>> selectDeptTree(Dept dept) {
        List<Dept> deptList = deptMapper.selectDeptList(dept);
        return initSimpleDataTree(deptList);
    }

    /**
     * 查询部门管理树（排除下级）
     *
     * @param dept 部门
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SimpleDataTree<Dept>> selectDeptTreeExcludeChild(Dept dept) {
        Long deptId = dept.getDeptId();
        List<Dept> deptList = deptMapper.selectDeptList(dept);
        deptList.removeIf(d -> d.getDeptId().intValue() == deptId
                || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return initSimpleDataTree(deptList);
    }

    /**
     * 根据角色ID查询部门（数据权限）
     *
     * @param role 角色对象
     * @return 部门列表（数据权限）
     */
    @Override
    public List<SimpleDataTree<Dept>> roleDeptTreeData(Role role) {
        Long roleId = role.getRoleId();
        List<SimpleDataTree<Dept>> simpleDataTrees;
        List<Dept> deptList = selectDeptList(new Dept());
        if (roleId != null) {
            List<String> roleDeptList = deptMapper.selectRoleDeptTree(roleId);
            simpleDataTrees = initSimpleDataTree(deptList, roleDeptList);
        } else {
            simpleDataTrees = initSimpleDataTree(deptList);
        }
        return simpleDataTrees;
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<SimpleDataTree<Dept>> initSimpleDataTree(List<Dept> deptList) {
        return initSimpleDataTree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList     部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<SimpleDataTree<Dept>> initSimpleDataTree(List<Dept> deptList, List<String> roleDeptList) {
        List<SimpleDataTree<Dept>> simpleDataTrees = new ArrayList<>();
        boolean isCheck = CollectionUtil.isNotEmpty(roleDeptList);
        for (Dept dept : deptList) {
            SimpleDataTree<Dept> simpleDataTree = new SimpleDataTree<>();
            simpleDataTree.setId(dept.getDeptId());
            simpleDataTree.setPId(dept.getParentId());
            simpleDataTree.setName(dept.getDeptName());
            simpleDataTree.setTitle(dept.getDeptName());
            if (isCheck) {
                simpleDataTree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                simpleDataTree.setSelected(simpleDataTree.isChecked());
            }
            simpleDataTree.setOriginObj(dept);
            simpleDataTrees.add(simpleDataTree);
        }
        return simpleDataTrees;
    }

    /**
     * 查询部门人数
     *
     * @param parentId 部门ID
     * @return 结果
     */
    @Override
    public int selectDeptCount(Long parentId) {
        QueryWrapper<Dept> selectDeptCount = Wrappers.<Dept>query()
                .eq(DeptMetadata.DEL_FLAG.getColName(), 0)
                .eq(parentId != null && parentId != 0, DeptMetadata.PARENT_ID.getColName(), parentId);
        return deptMapper.selectCount(selectDeptCount);
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        QueryWrapper<User> checkDeptExistUser = Wrappers.<User>query()
                .eq(DeptMetadata.DEPT_ID.getColName(), deptId)
                .eq(DeptMetadata.DEL_FLAG.getColName(), 0);
        int result = userMapper.selectCount(checkDeptExistUser);
        return result > 0;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        UpdateWrapper<Dept> updateWrapper = Wrappers.<Dept>update()
                .set(DeptMetadata.DEL_FLAG.getColName(), 2)
                .eq(DeptMetadata.DEPT_ID.getColName(), deptId);
        return deptMapper.update(null, updateWrapper);
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(Dept dept) {
        Dept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new HimioException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insert(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(Dept dept) {
        Dept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        Dept oldDept = selectDeptById(dept.getDeptId());
        if (newParentDept != null && oldDept != null) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(Dept dept) {
        dept = deptMapper.selectDeptById(dept.getDeptId());
        dept.setModifiedByName(dept.getModifiedByName());
        dept.setModifiedBy(dept.getModifiedBy());
        dept.setGmtModified(LocalDateTime.now());
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<Dept> children = deptMapper.selectChildrenDeptById(deptId);
        for (Dept child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public Dept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(Dept dept) {
        long deptId = dept.getDeptId() == null ? -1L : dept.getDeptId();
        QueryWrapper<Dept> checkDeptNameUnique = Wrappers.<Dept>query()
                .eq(DeptMetadata.DEPT_NAME.getColName(), dept.getDeptName())
                .eq(DeptMetadata.PARENT_ID.getColName(), dept.getParentId())
                .last("limit 1");
        Dept info = deptMapper.selectOne(checkDeptNameUnique);
        if (info != null && info.getDeptId() != deptId) {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }
}
